package me.tonywang.common.service.impl;

import com.baomidou.mybatisplus.MybatisSqlSessionTemplate;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import me.tonywang.common.result.PageInfo;
import me.tonywang.common.result.Tree;
import me.tonywang.common.util.JsonUtils;
import me.tonywang.common.util.StringUtils;
import me.tonywang.common.service.ICommonQryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommonQryServiceImpl implements ICommonQryService {

      protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "mybatisSqlSessionTemplate")
    MybatisSqlSessionTemplate mybatisSqlSessionTemplate ;


    @Override
    public PageInfo dataGrid(String statement, Map<String, Object> condition,
                             int current, int size, String sort, String order) {
        logger.debug("condition :" + condition);
        Pagination page  = new Pagination(current, size );

        //deal for mybatis foreach
        for ( String  key : condition.keySet()) {
            if(key.endsWith("List")&&condition.get(key)!=null){
                condition.put(key+"New", StringUtils.commaDelimitedListToStringArray(condition.get(key).toString()));
            }
        }

        List<Map<String,Object>> result = mybatisSqlSessionTemplate.selectList(statement, condition,page);
        PageInfo pageInfo = new PageInfo(current, size, sort, order);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setRows(result);
        return pageInfo;
    }

    @Override
    public List<Tree> selectTree(String statement, Map<String, Object> condition) {
        List<Map<String, Object>> result = mybatisSqlSessionTemplate.selectList(statement, condition);
        List<Tree> trees = new ArrayList<Tree>();
        for (Map<String, Object> node : result) {
            Tree tree = new Tree();
            tree.setId(StringUtils.toString(node.get("id")));
            tree.setPid(StringUtils.toString(node.get("pid")));
            tree.setText(StringUtils.toString(node.get("text")));
            tree.setIconCls(StringUtils.toString(node.get("iconCls")));
            tree.setAttributes(JsonUtils.toJson(node.get("attributes")));
            tree.setOpenMode(StringUtils.toString(node.get("openMode")));
            tree.setState(StringUtils.toString(node.get("state")));
            trees.add(tree);
        }
        return trees;
    }

    @Override
    public List dataList(String statement, Map<String, Object> condition) {
        return mybatisSqlSessionTemplate.selectList(statement,condition);
    }
}
